<template>
  <div class="container" v-loading="loading">
    <img id="photo" :src="defaultImg" width="640" height="480" />
    <div class="dialog-footer-btn">
      <el-button type="default" @click="emit('close')">取消</el-button>
      <el-button
        type="primary"
        :disabled="init_status"
        @click="start('sGetBase64')"
      >
        保存
      </el-button>
    </div>
  </div>
</template>

<script setup name='camera'>
import { ElMessageBox, ElMessage } from 'element-plus'
var TotalTimelenth = 0
var timer
var str1
var str2
var begin_data = 'data:image/jpeg;base64,'

let defaultQuality = ref(100)
let idCard = ref('')
const loading = ref(false)
let webSocket = ref(null)
let mainCameras = ref(true)
let file = ref(null)
let init_status = ref(true)
let emit = defineEmits(['pushFileList', 'closeReadLoading', 'getIdCard','close'])
let defaultImg = new URL(
  `../../assets/img/common/high_loading.gif`,
  import.meta.url
).href
const freshPage = e => {
  closeWebsocket()
}

const changeQuality = val => {
  console.log(val)
  start(`vSetImageQuality(${val})`)
}
const send_file = () => {
  if (file.value) {
    loading.value = false
    emit('pushFileList', file.value)
  }
}
const transform_imgBase64 = (base64, filename) => {
  var arr = base64.split(',')
  var mime = arr[0].match(/:(.*?);/)[1]
  var bstr = atob(arr[1])
  var n = bstr.length
  var u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, { type: mime })
}
const change_cameras = () => {
  start('bStopPlay')
  setTimeout(() => {
    if (mainCameras.value) {
      start('bStartPlay2')
    } else {
      start('bStartPlay')
    }
  }, 500)
}
// 关闭socket
const closeWebsocket = () => {
  start('bStopPlay')
  if (webSocket) {
    webSocket.close()
  }
}
const connectWebsocket = () => {
  webSocket = new WebSocket('ws://localhost:1818')
  window.onbeforeunload = function () {
    webSocket.send('bStopPlay()')
    webSocket.send('bStopPlay4()')
  }
  webSocket.onerror = function (event) {
    onError(event)
  }

  webSocket.onopen = function (event) {
    onOpen(event)
  }

  webSocket.onclose = function (event) {
    onClose(event)
    webSocket.send('bStopPlay()')
    webSocket.send('bStopPlay4()')
  }

  webSocket.onmessage = function (event) {
    onMessage(event)
  }
}
const onMessage = event => {
  if (event.data.indexOf('BarCodeTransferBegin') >= 0) {
  } else if (
    event.data.indexOf('BeginbStartPlaytrueEndbStartPlay') >= 0 ||
    event.data.indexOf('BeginbStartPlay2trueEndbStartPlay2') >= 0
  ) {
    init_status.value = false
  } else if (event.data.indexOf('BeginsGetBase64') >= 0) {
    console.log('保存')
    //document.getElementById("preview").src = begin_data + event.data.substring(0, event.data.length - 11);
    //ElMessage.success(event.data.replace('BeginBase64','').replace('EndBase64',''));
    let res = event.data
      .replace('BeginsGetBase64', '')
      .replace('EndsGetBase64', '')
    let base64 = 'data:image/jpeg;base64,' + res
    file.value = transform_imgBase64(base64, 'text.jpg')
    send_file()
  } else if (event.data.indexOf('BeginbSaveJPGtrueEndbSaveJPG') >= 0) {
    ElMessage.success('保存成功至D盘根目录')
  } else if (event.data.indexOf('BeginReadCard') >= 0) {
    idCard.value = JSON.parse(
      event.data.replace('BeginReadCard', '').replace('EndReadCard', '')
    )
    if (idCard.value.IdNo || idCard.value.result == 1) {
      emit('getIdCard', idCard.value)
    } else {
      emit('getIdCard', null)
      ElMessage.error('未识别出信息，请将身份证调整方向后重试')
    }
    closeWebsocket()
  } else if (
    event.data.indexOf('BeginvSetImageQualitytrueEndvSetImageQuality') >= 0
  ) {
    document.getElementById('photo').src = defaultImg
  } else {
    document.getElementById('photo').src = begin_data + event.data
  }
}
const onError = event => {
  ElMessage.error('设备未连接，请将设备连接电脑')
  emit('closeReadLoading')
  document.getElementById('photo').src = ''
}
const onClose = event => {
  webSocket.send('bStopPlay()')
  webSocket.send('bStopPlay4()')
}
const onOpen = event => {}
const TimeGo = () => {
  TotalTimelenth++
  var Hour, Minue, Second
  Hour = Math.floor(TotalTimelenth / 3600)
  Minue = Math.floor((TotalTimelenth / 60) % 60)
  Second = Math.floor(TotalTimelenth % 60)
  TimeLenth.value = Hour + '时' + Minue + '分' + Second + '秒'
}
const start = el => {
  // loading.value = true
  if (el === 'bStartPlay') {
    mainCameras.value = true
  } else if (el === 'bStartPlay2') {
    mainCameras.value = false
  }
  if (el == 'bStartRec(d:\\test.avi)') {
    timer = window.setInterval('TimeGo()', 1000)
  }
  if (el == 'bStopRec') {
    window.clearInterval(timer)
    TotalTimelenth = 0
    ElMessage.error('录屏结束')
  }
  // ReadCard(1001,D:\\)
  if (webSocket.readyState === 1) {
    webSocket.send(el)
  } else if (webSocket.readyState === 2) {
    webSocket.close()
    setTimeout(() => {
      connectWebsocket()
    }, 500)
    setTimeout(() => {
      webSocket.onopen = function (event) {
        start('bStartPlay2')
      }
    }, 600)
    setTimeout(() => {
      webSocket.send(el)
    }, 1000)
  } else if (webSocket.readyState === 0) {
    setTimeout(() => {
      webSocket.send(el)
    }, 1000)
  } else {
    setTimeout(() => {
      connectWebsocket()
    }, 500)
    setTimeout(() => {
      webSocket.onopen = function (event) {
        start('bStartPlay2')
      }
    }, 600)
    setTimeout(() => {
      webSocket.send(el)
    }, 1000)
  }
  return false
}

onMounted(() => {
  webSocket.onopen = function (event) {
    start('bStartPlay')
    start(`vSetImageQuality(100)`)
  }
})
onBeforeMount(() => {
  init_status.value = true
  window.addEventListener('beforeunload', e => freshPage(e))
  connectWebsocket()
})

defineExpose({
  closeWebsocket
})
</script>
<style lang="scss" scoped>
/* 弹窗提交时loading样式需占满整个弹窗 */
.el-loading-parent--relative {
  position: inherit !important;
}
.container {
  display: flex;
  justify-content: center;
  .options {
    padding: 0 10px;
  }
  .btn-box {
    display: flex;
    align-items: center;
    .label {
      margin-right: 10px;
    }
  }
}
</style>